package com.raysweather.android;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.Timer;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

public class POTD extends Activity {

	private Timer timer;
	private RaysWeather rw;
	private POTDList potdList = null;
	private int updateDelay = 15;
	private static POTD potd;
	Drawable d = null;
	private ProgressDialog pd;
	BroadcastReceiver bReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if(action.equalsIgnoreCase("update_two")){    
				update();
			}
		}
	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		potd = this;
		setContentView(R.layout.potd);
		registerReceiver(bReceiver, new IntentFilter("update_two"));
		rw = RaysWeather.getInstance();
		if(rw.getPotdUrl() != null)
			update();
	}

	private void update(){
		Drawable d = LoadImageFromWebOperations(rw.getPotdUrl());
		((ImageView)findViewById(R.id.potd_image)).setImageDrawable(d);
		((TextView)findViewById(R.id.potd_text)).setText(rw.getPotdText());
	}

	private Drawable LoadImageFromWebOperations(String url)
	{
		InputStream in = null;
		try {
			in = new java.net.URL(url).openStream();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Bitmap bmp = BitmapFactory.decodeStream(new PatchInputStream(in));
		return new BitmapDrawable(bmp);
	}

	public class PatchInputStream extends FilterInputStream {
		public PatchInputStream(InputStream in) {
			super(in);
		}
		public long skip(long n) throws IOException {
			long m = 0L;
			while (m < n) {
				long _m = in.skip(n-m);
				if (_m == 0L) break;
				m += _m;
			}
			return m;
		}
	}

}